/*
 * VariableStringSerializer.cpp
 *
 *  Created on: Oct 26, 2012
 *      Author: m
 */

#include "VariableStringSerializer.h"

namespace physical
{

VariableStringSerializer::VariableStringSerializer()
{
}

VariableStringSerializer::~VariableStringSerializer()
{
}


size_t VariableStringSerializer::serialize( const std::string &element, byteStream block )
{
    str_size_t strLength = element.length();

    // Serializar la longitud y luego el c_string
    assert( strLength <= 255 );

    memcpy( block, &strLength, sizeof(str_size_t) );
    memcpy( block + sizeof(str_size_t), element.c_str(), strLength );

    size_t totalWrittenBytes = strLength + sizeof(str_size_t);

    return totalWrittenBytes;
}

size_t VariableStringSerializer::deserialize( const byteStream block, std::string &element )
{
    str_size_t strLength = block[0];
    size_t bytesCount = sizeof( str_size_t );

    std::unique_ptr<char[]> str( new char[strLength + 1] );

    if ( strLength > 0 )
    {
        memcpy( str.get(), block + 1, strLength );
        bytesCount += strLength;
    }

    str[strLength] = '\0';

    // TODO: revisar esto!
    element.assign( str.get() );

    return bytesCount;
}

size_t VariableStringSerializer::computeSize( const std::string &element )
{
    size_t serializationSize = element.length() + sizeof( str_size_t );
    return serializationSize;
}

size_t VariableStringSerializer::serialize( const _T_ptr &elementPtr,
        byteStream block )
{
    return this->serialize( *elementPtr, block );
}

size_t VariableStringSerializer:: VariableStringSerializer::deserialize(
        const byteStream block, _T_ptr &elementPtr )
{
    elementPtr.reset( new std::string );
    return this->deserialize( block, *elementPtr );
}

size_t VariableStringSerializer::computeSize( const _T_ptr &elementPtr )
{
    return this->computeSize( *elementPtr );
}

}
